package api

import (
	"cs/models"
	"cs/request"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetMenus(c *gin.Context) {
	menus, _ := models.GetAllMenu()

	c.JSON(http.StatusOK, gin.H{"status": "success", "menus": menus})
}

func AddMenu(c *gin.Context) {
	var form request.AddMenuForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}

	menu := models.Menu{
		Name:     form.Name,
		Route:    form.Route,
		Icon:     form.Icon,
		Sort:     form.Sort,
		ParentId: form.ParentId,
	}
	if err := models.AddMenu(menu); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "data": menu})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func GetMenuTree(c *gin.Context) {
	menus, _ := models.GetAllMenu()
	tree := models.GenTree(0, menus)

	c.JSON(http.StatusOK, gin.H{"status": "success", "menus": tree})
}

func GetTopMenu(c *gin.Context) {
	menus, err := models.GetTopMenu()
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "menus": menus})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func GetSubmenu(c *gin.Context) {
	menus, err := models.GetSubmenu()
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "menus": menus})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func GetMyselfMenu(c *gin.Context) {
	uid, _ := c.Get("user_id")
	menus, err := models.GetMenuByUid(uid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
		return
	}

	if len(menus) > 1 {
		//生成树形结构
		tree := models.GenTree(0, menus)
		c.JSON(http.StatusOK, gin.H{"status": "success", "menus": tree})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "success", "menus": menus})
	}
}

func UpdateMenu(c *gin.Context) {
	var form request.UpdateMenuForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}

	err := models.UpdateMenu(form.ID, map[string]interface{}{
		"name":     form.Name,
		"route":    form.Route,
		"icon":     form.Icon,
		"sort":     form.Sort,
		"parentId": form.ParentId,
	})
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func DelMenu(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	has := models.MenuHasChild(id)
	if has {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": "该菜单下有子菜单!删除子菜单后,才能删除"})
		return
	}

	if err := models.DelMenu(id); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}
